<?php
namespace Modules\Category\Http\Controllers\Client\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Category\Entities\Category;

use Validator;
use ThrowException;

class CategoryController extends Controller
{
    public function index(Request $req, $categoryType)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $options = $req->all();

        $options['scopes'] = [
            'type' => $categoryType
        ]; 

        // 如果分类等级不指定为所有等级，则仅返回一级分类
        if ($req->input('level_mode') !== 'all') {
            $options['scopes']['level'] = 1;
        }

        $options['where']['is_listed'] = 1;

        $options['order_by'] = ['list_weight' => 'desc'];

        $options['with'] = ['sub_categories'];

        $options['with_count'] = ['onstock_boxes', 'onstock_products'];

        $options['only'] = [
            'id',
            'uuid',
            'thumb',
            'title',
            'sub_title',
            // 'list_weight',
            // 'is_listed',
            // 'description',
            // 'products_count',
            'level',
            'item_total',
            'sub_categories' => [
                '*' => [
                    'id',
                    'uuid',
                    'title',
                    'sub_title',
                    'thumb',
                ]
            ],
            // 'created_at'
        ];

        $list = Category::getList($options);

        $list->each(function ($item) {
           $item->item_total = $item->onstock_boxes_count + $item->onstock_products_count;
        });

        return $list->generateListResponse();
    }

    public function show(Request $req, $uuidOrId)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $category = Category::where('id', $uuidOrId)->orWhere('uuid', $uuidOrId)->first();

        $info = $category->getInfo();

        return [
            'info' => $info
        ];
    }
}
